package com.gpnu7_412.yanzhi.controller.user;

import com.gpnu7_412.yanzhi.entity.User;
import com.gpnu7_412.yanzhi.exception.custom.DataInconsistencyException;
import com.gpnu7_412.yanzhi.service.UserService;
import com.gpnu7_412.yanzhi.status.Impl.ResultCode;
import com.gpnu7_412.yanzhi.util.Result;
import com.gpnu7_412.yanzhi.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author HJJ
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class DeleteController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 删除用户
     * @return 响应数据
     */
    @PostMapping("/delete")
    public Result deleteAllMessage(@RequestBody Map<String, Object> requestMap) {
        String verification = (String) requestMap.get("verification");
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        User user = userService.selectUserById(userId);
        // 尝试从 Redis 中取出验证码
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String storeCode = operations.get(user.getEmail());
        // 验证码校验
        if (storeCode == null || !storeCode.equals(verification)) {
            throw new DataInconsistencyException("验证码错误");
        }
        userService.deleteUser((Integer) map.get("userId"));
        return new Result(ResultCode.SUCCESS, "注销成功");
    }
}
